package com.minelx.statementplus.ui.form.swing;

import com.minelx.sqlstructures.core.database.IDatabase;
import com.minelx.sqlstructures.core.table.ITable;
import com.minelx.sqlstructures.core.values.FieldValues;
import com.minelx.util.common.Node;
import com.minelx.util.common.TreeNode;

import javax.swing.tree.DefaultMutableTreeNode;
import java.util.Collections;
import java.util.List;

import static java.util.stream.Collectors.toList;

public class DatabaseToNode {
	public DefaultMutableTreeNode toNode(IDatabase database) {
		TreeNode<Object> node = new TreeNode<>(new NodeAdapter(database));
		return node.convert(DefaultMutableTreeNode::new, DefaultMutableTreeNode::add);
	}

	// FIXME 2021/7/26  wait for me!!!     test
	public static class NodeAdapter implements Node<Object> {
		private final Object root;

		public NodeAdapter(Object root) {
			this.root = root;
		}

		@Override
		public List<? extends Node<Object>> children() {
			if (root instanceof IDatabase) {
				IDatabase database = (IDatabase) root;
				return database.getTables().stream().map(NodeAdapter::new).collect(toList());
			} else if (root instanceof ITable) {
				ITable table = (ITable) root;
				return table.getFields().stream().map(NodeAdapter::new).collect(toList());
			} else if (root instanceof FieldValues) {
				return Collections.emptyList();
			}
			throw new RuntimeException("something is wrong here");
		}

		@Override
		public Object get() {
			return root;
		}
	}
}
